package com.situ.mall.listener;

import com.situ.mall.constant.MqConstant;
import com.situ.mall.constant.OrderStatusConstant;
import com.situ.mall.mapper.OrderMapper;
import com.situ.mall.pojo.Order;
import com.situ.mall.service.IOrderService;
import com.situ.mall.util.MultiDelayMessage;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalTime;

@Component
public class SpringRabbitListener {
    @Autowired
    private IOrderService orderService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(MqConstant.DELAY_ORDER_QUEUE),
            exchange = @Exchange(name = MqConstant.DELAY_EXCHANGE, delayed = "true"), //type类型是：x-delayed-message
            key = MqConstant.DELAY_ORDER_ROUTING_KEY
    ))
    public void listenDelayMessage(MultiDelayMessage message) {
        System.out.println("SpringRabbitListener.listenDelayMessage: "+message);
        Long orderNo =(Long) message.getData();
        Order order = orderService.selectById(orderNo);
        if(order==null || order.getStatus()>1){
            return;
        }
        System.out.println("SpringRabbitListener.listenDelayMessage");
        if(message.hasNextDelay()){
            System.out.println("接受延迟消息");
            Long delayValue = message.removeNextDelay();
            rabbitTemplate.convertAndSend(MqConstant.DELAY_EXCHANGE,MqConstant.DELAY_ORDER_ROUTING_KEY, message,new MessagePostProcessor() {
                @Override
                public Message postProcessMessage(Message message) throws AmqpException {
                    message.getMessageProperties().setDelayLong(delayValue);
                    return message;
                }
            });
        }
        //无剩余时间且未支付
        else{
            orderService.updateStatus(orderNo, OrderStatusConstant.ORDER_STATUS_CANCLE);
        }
    }
}
